/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * EnderecoDialog.java
 *
 * Created on 25/10/2011, 17:46:40
 */
package br.com.seguradora.view.dialog;

import br.com.seguradora.exception.InputValidationException;
import br.com.seguradora.exception.PersistenciaException;
import br.com.seguradora.model.Endereco;
import br.com.seguradora.model.constant.UnidadeFederativa;
import br.com.seguradora.service.EnderecoService;
import br.com.seguradora.view.ErrorsList;
import br.com.seguradora.view.StateEntityWindow;
import br.com.seguradora.view.UserError;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.Iterator;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;

/**
 *
 * @author Diego
 */
public class EnderecoDialog extends javax.swing.JDialog {
    
    private final static String titleWindow = "Endereço";
    private StateEntityWindow stateEntity;
    private Endereco endereco;
    
    public EnderecoDialog(java.awt.Frame parent, boolean modal, StateEntityWindow stateEntity, Endereco endereco) {
        super(parent, modal);
        initComponents();
        this.stateEntity = stateEntity;
        setTitle(titleWindow + stateEntity);
        setEndereco(endereco);
        organizeWindow();
        setLocationRelativeTo(null);
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSeparator1 = new javax.swing.JSeparator();
        confirmarButton = new javax.swing.JButton();
        cancelarButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        cepField = new javax.swing.JFormattedTextField();
        jLabel2 = new javax.swing.JLabel();
        logradouroField = new javax.swing.JTextField();
        logradouroErrorLabel = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        bairroField = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        cidadeField = new javax.swing.JTextField();
        bairroErrorLabel = new javax.swing.JLabel();
        cidadeErrorLabel = new javax.swing.JLabel();
        cepErrorLabel = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        estadoCombo = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        confirmarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/accept.png"))); // NOI18N
        confirmarButton.setText("Confirmar");
        confirmarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                confirmarButtonActionPerformed(evt);
            }
        });

        cancelarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/cross.png"))); // NOI18N
        cancelarButton.setText("Cancelar");
        cancelarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelarButtonActionPerformed(evt);
            }
        });

        jLabel1.setText("CEP:");

        try {
            cepField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("#####-###")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        cepField.setToolTipText("Digite o cep e tecle ENTER para localizar o endereço");
        cepField.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);

        jLabel2.setText("Logradouro:");

        logradouroErrorLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/exclamation.png"))); // NOI18N

        jLabel3.setText("Bairro:");

        jLabel4.setText("Cidade:");

        bairroErrorLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/exclamation.png"))); // NOI18N

        cidadeErrorLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/exclamation.png"))); // NOI18N

        cepErrorLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/exclamation.png"))); // NOI18N

        jLabel5.setText("Estado:");

        estadoCombo.setModel(new DefaultComboBoxModel(UnidadeFederativa.values()));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(36, 36, 36)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel5)
                    .addComponent(jLabel4)
                    .addComponent(jLabel3)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(cepField, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cepErrorLabel))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(logradouroField, javax.swing.GroupLayout.PREFERRED_SIZE, 404, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(logradouroErrorLabel))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(cidadeField, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(bairroField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 244, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cidadeErrorLabel)
                            .addComponent(bairroErrorLabel)))
                    .addComponent(estadoCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(19, Short.MAX_VALUE))
            .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 556, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(112, 112, 112)
                .addComponent(confirmarButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cancelarButton)
                .addContainerGap(244, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(cepField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(cepErrorLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 20, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 4, Short.MAX_VALUE)
                        .addComponent(jLabel2)
                        .addGap(8, 8, 8))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(logradouroErrorLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 20, Short.MAX_VALUE)
                            .addComponent(logradouroField))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(bairroErrorLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(bairroField)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel4)
                        .addComponent(cidadeField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(cidadeErrorLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 20, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(estadoCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(confirmarButton)
                    .addComponent(cancelarButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarButtonActionPerformed
        dispose();
    }//GEN-LAST:event_cancelarButtonActionPerformed
    
    private void confirmarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_confirmarButtonActionPerformed
        try {
            validateUserInput();
            EnderecoService enderecoService = new EnderecoService();
            Endereco endereco = getEndereco();
            if (getStateEntity() == StateEntityWindow.NEW) {
                enderecoService.inserir(endereco);
            } else if (getStateEntity() == StateEntityWindow.UPDATE) {
                enderecoService.atualizar(endereco);
            }
            dispose();
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        } catch (InputValidationException ivex) {
            JOptionPane.showMessageDialog(null, "Erros foram encontrados.", "Mensagem do sistema", JOptionPane.ERROR_MESSAGE);
            ErrorsList errorsList = ivex.getErrorsList();
            for (Iterator<UserError> it = errorsList.iterator(); it.hasNext();) {
                UserError userError = it.next();
                showErrorLabel(userError);
            }
        }
    }//GEN-LAST:event_confirmarButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
            System.out.println(ex);
        }
        //</editor-fold>
        
        java.awt.EventQueue.invokeLater(new Runnable() {
            
            public void run() {
                EnderecoDialog dialog = new EnderecoDialog(new javax.swing.JFrame(), true, StateEntityWindow.NEW, null);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel bairroErrorLabel;
    private javax.swing.JTextField bairroField;
    private javax.swing.JButton cancelarButton;
    private javax.swing.JLabel cepErrorLabel;
    private javax.swing.JFormattedTextField cepField;
    private javax.swing.JLabel cidadeErrorLabel;
    private javax.swing.JTextField cidadeField;
    private javax.swing.JButton confirmarButton;
    private javax.swing.JComboBox estadoCombo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel logradouroErrorLabel;
    private javax.swing.JTextField logradouroField;
    // End of variables declaration//GEN-END:variables

    private void setEndereco(Endereco endereco) {
        if (endereco == null) {
            return;
        }
        this.endereco = endereco;
        cepField.setText(endereco.getCep());
        logradouroField.setText(endereco.getLogradouro());
        bairroField.setText(endereco.getBairro());
        cidadeField.setText(endereco.getCidade());
        estadoCombo.setSelectedItem(endereco.getUf());
    }
    
    private Endereco getEndereco() {
        if (endereco == null) {
            endereco = new Endereco();
        }
        endereco.setCep(cepField.getText().replace("-", ""));
        endereco.setLogradouro(logradouroField.getText().toUpperCase());
        endereco.setBairro(bairroField.getText().toUpperCase());
        endereco.setCidade(cidadeField.getText().toUpperCase());
        endereco.setUf(UnidadeFederativa.valueOf(estadoCombo.getSelectedItem().toString()));
        return endereco;
    }
    
    private void organizeWindow() {
        if (getStateEntity() == StateEntityWindow.NEW) {
            estadoCombo.setSelectedItem(UnidadeFederativa.PE);
        }
        isShowErrorsLabel(false);
    }
    
    public StateEntityWindow getStateEntity() {
        return stateEntity;
    }
    
    private void isShowErrorsLabel(boolean show) {
        cepErrorLabel.setVisible(show);
        logradouroErrorLabel.setVisible(show);
        bairroErrorLabel.setVisible(show);
        cidadeErrorLabel.setVisible(show);
    }
    
    private void showErrorLabel(UserError userError) {
        userError.getLabel().setVisible(true);
    }
    
    private void validateUserInput() throws InputValidationException {
        isShowErrorsLabel(false);
        ErrorsList errorsList = new ErrorsList();
        if (cepField.getText().equals("     -   ")) {
            errorsList.addError(new UserError(cepErrorLabel, "O cep não foi informado corretamente."));
        }
        if (logradouroField.getText().isEmpty()) {
            errorsList.addError(new UserError(logradouroErrorLabel, "O logradouro não foi informado."));
        }
        if (bairroField.getText().isEmpty()) {
            errorsList.addError(new UserError(bairroErrorLabel, "O bairro não foi informado."));
        }
        if (cidadeField.getText().isEmpty()) {
            errorsList.addError(new UserError(cidadeErrorLabel, "A cidade não foi informada."));
        }
        if (errorsList.countErrors() > 0) {
            throw new InputValidationException(errorsList);
        }
    }
    
    public Endereco objetoEndereco() {
        return endereco;
    }
    
    @Override
    protected JRootPane createRootPane() {
        ActionListener closeListener = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                cancelarButtonActionPerformed(e);
            }
        };
        KeyStroke stroke =
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
        JRootPane myRootPane = new JRootPane();
        myRootPane.registerKeyboardAction(
                closeListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);

        return myRootPane;
    }
}
